package com.xiaoyung.easyisapisdk.common.util.bean;


import java.util.Date;

import com.xiaoyung.easyisapisdk.common.util.DateUtils;



public class MyDateConverter extends org.apache.commons.beanutils.converters.DateTimeConverter{
	public MyDateConverter() {
		super();
	}

	public MyDateConverter(Object defaultValue) {
		super(defaultValue);
	}
	
	@Override
	protected Class<?> getDefaultType() {
		return Date.class;
	}
	
	@Override
	public <T> T convert(Class<T> type, Object value) {
		if (type.isAssignableFrom(Date.class)) {
			try {
				return convertToType(type,value);
			} catch (Exception e) {
				if(e instanceof RuntimeException) {
					throw (RuntimeException)e;
				}else {
					throw new RuntimeException(e);
				}
			}
		}
		return super.convert(type, value);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected <T> T convertToType(Class<T> targetType, Object value) throws Exception {
		if (targetType.isAssignableFrom(Date.class)) {
			//com.easyis.apaas.common.core.utils.DateUtils.parseDate(Object)
			if(value==null) {
				return null;
			}
			java.util.Date date  = null;
			if(value instanceof String ) {
				date =  DateUtils.parseDate((String)value);
			}else if(value instanceof Long ) {
				date = new Date((Long)value);
			}
			return (T) date;
		}
		return super.convertToType(targetType, value);
	}

}
